package com.im.partchat.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.im.partchat.R;
import com.im.partchat.adapter.SelectPersonAdapter;
import com.im.partchat.base.BaseActivity;
import com.im.partchat.bean.User;
import com.im.partchat.mvp.persenter.ContactPresenter;
import com.im.partchat.utils.Navigation;
import com.im.partchat.widget.ClearEditText;
import com.im.partchat.widget.LetterListViewV2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by hhz on 2017/7/3.
 */
public class SelectFriendsActivity extends BaseActivity implements SelectPersonAdapter.UpdateChoose {
    @BindView(R.id.search_button)
    TextView searchButton;
    @BindView(R.id.poupwindow_search_view)
    ClearEditText searchEt;
    @BindView(R.id.content_list_view)
    ListView memberLv;
    @BindView(R.id.MyLetterListView)
    LetterListViewV2 letterListView;
    @BindView(R.id.search_contacts_listView)
    ListView searchLv;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.tv_letter_pop)
    TextView letterPop;

    private MenuItem confiemItem;
    private ContactPresenter presenter;

    public static final ArrayList<User> choosed = new ArrayList<>();
    private SelectPersonAdapter searchAdapter;
    private SelectPersonAdapter memberAdapter;
    private List<User> memList = new ArrayList<>();
    private List<User> searchList = new ArrayList<>();
    private HashMap<String, Integer> alphaIndexer = new HashMap<>();;
    private List<String> sections = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_select_person;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        View headerView = LayoutInflater.from(this).inflate(R.layout.select_person_header, null);
        TextView groupBtn = (TextView) headerView.findViewById(R.id.jingyuan_choose_group);
        groupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Navigation.navigateGroup();
            }
        });
        memberLv.addHeaderView(headerView);
        memberAdapter = new SelectPersonAdapter(memList, this, this);
        memberAdapter.setShowCheckBox(true);
        memberAdapter.setWordVisible(true);
        memberLv.setAdapter(memberAdapter);
        memberLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            }
        });
        letterListView
                .setOnTouchingLetterChangedListener(new LetterListViewListener());
        letterListView.setPop(letterPop);
        searchAdapter = new SelectPersonAdapter(searchList, this, this);
        searchAdapter.setWordVisible(false);
        searchAdapter.setShowCheckBox(true);
        searchLv.setAdapter(searchAdapter);
        searchLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            }
        });
        memberLv.setOnScrollListener(onScrollListener);
        searchLv.setOnScrollListener(onScrollListener);
        searchEt.setCursorVisible(false);
        searchEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEt.setCursorVisible(true);
            }
        });
        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void searchData(String param) {

        if (TextUtils.isEmpty(param)) {
            searchList.clear();
            searchAdapter.notifyDataSetChanged();
            searchEt.setCursorVisible(false);
            searchLv.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.GONE);
            return;
        }
        presenter.getUserByKey(param);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_confirm, menu);
        confiemItem = menu.findItem(R.id.action_confirm);
        confiemItem.setEnabled(false);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.action_confirm) {

        }
        return super.onMenuItemClick(item);
    }

    private AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                hideKeyBoard();
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    };

    /**
     * 拼音检索表监听
     */
    private class LetterListViewListener implements LetterListViewV2.OnTouchingLetterChangedListener {
        @Override
        public void onTouchingLetterChanged(final String s) {
            if (alphaIndexer != null && alphaIndexer.get(s) != null) {
                hideKeyBoard();
                int position = alphaIndexer.get(s) + memberLv.getHeaderViewsCount();
                memberLv.setSelection(position);
            }
        }
    }

    /**
     * 隐藏键盘
     */
    public void hideKeyBoard() {
        InputMethodManager inputMethodManager = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
    }

    @Override
    public void update() {
        if (choosed.size() > 0) {
            confiemItem.setEnabled(true);
            confiemItem.setTitle("确定(" + choosed.size() + ")");
        } else {
            confiemItem.setTitle("确定");
            confiemItem.setEnabled(false);
        }
        if (searchLv.getVisibility() == View.VISIBLE) {
            memberAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void initData() {
        presenter = new ContactPresenter(this);
        presenter.getFriends();
    }

    @Override
    public void onLoadDataSuccess(Object o, String flag) {
        if ("getFriends".equals(flag)) {
            if (o == null) {

            } else {
                List<User> users = (List<User>) o;
                memList.clear();
                memList.addAll(users);
                memberAdapter.notifyDataSetChanged();
                sections.clear();
                initAlphaIndexer();
                letterListView.setAlphas(sections);
                letterListView.invalidate();
            }

        } else if ("getUserByKey".equals(flag)) {
            if (o == null) {
                tvEmpty.setVisibility(View.VISIBLE);
                searchLv.setVisibility(View.GONE);
            } else {
                List<User> users = (List<User>) o;
                searchList.clear();
                searchList.addAll(users);
                searchAdapter.notifyDataSetChanged();

                searchEt.setCursorVisible(true);
                if (searchList.size() <= 0) {
                    tvEmpty.setVisibility(View.VISIBLE);
                    searchLv.setVisibility(View.GONE);
                } else {
                    tvEmpty.setVisibility(View.GONE);
                    searchLv.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    /**
     * 初始化拼音首字母和列表索引
     */
    private void initAlphaIndexer() {
        if (!memList.isEmpty()) {
            for (int i = 0; i < memList.size(); i++) {
                // 当前汉语拼音首字母
                String currentStr = getAlpha(memList.get(i).getJp());
                // 上一个汉语拼音首字母，如果不存在为“ ”
                String previewStr = (i - 1) >= 0 ? getAlpha(memList.get(i - 1)
                        .getJp()) : " ";
                if (!previewStr.equals(currentStr)) {
                    String name = getAlpha(memList.get(i).getJp());
                    alphaIndexer.put(name, i);
                    sections.add(name);
                }
            }
        }
    }

    /**
     * 获取拼音简拼首字母
     *
     * @param str
     * @return
     */
    private String getAlpha(String str) {
        if (str == null) {
            return "#";
        }
        if (str.trim().length() == 0) {
            return "#";
        }
        char c = str.trim().substring(0, 1).charAt(0);
        // 正则表达式，判断首字母是否是英文字母
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");
        if (pattern.matcher(c + "").matches()) {
            return (c + "").toUpperCase(Locale.getDefault());
        } else {
            return "#";
        }
    }

    @OnClick(R.id.search_button)
    public void onClick() {
    }
}
